import tkinter as tk
from tkinter import ttk, messagebox
import pymysql

# 数据库连接配置
DB_CONFIG = {
    "host": "localhost",
    "user": "root",
    "password": "123456",
    "db": "qimo",
    "charset": "utf8mb4",
}

# 连接数据库
def connect_db():
    try:
        return pymysql.connect(**DB_CONFIG)
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"无法连接到数据库: {e}")
        return None

# 查询用户信息
def query_user(username, password):
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM User WHERE Username = %s AND Password = %s"
            cursor.execute(query, (username, password))
            return cursor.fetchone()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询用户信息时出错: {e}")
        return None
    finally:
        connection.close()

# 审核教室申请
def review_application(application_id, status):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "UPDATE ClassroomApplication SET Status = %s WHERE ApplicationID = %s"
            cursor.execute(query, (status, application_id))
            connection.commit()
            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"审核教室申请时出错: {e}")
        return False
    finally:
        connection.close()

# 审核教室申请详情
def review_application_detail(self, application):
    review_window = tk.Toplevel(self)
    review_window.title("审核教室申请")

    ttk.Label(review_window, text="申请编号:").grid(row=0, column=0, padx=5, pady=5)
    application_id_entry = ttk.Entry(review_window)
    application_id_entry.grid(row=0, column=1, padx=5, pady=5)
    application_id_entry.insert(0, application[0])
    application_id_entry.config(state='readonly')

    ttk.Label(review_window, text="教室编号:").grid(row=1, column=0, padx=5, pady=5)
    applicant_id_entry = ttk.Entry(review_window)
    applicant_id_entry.grid(row=1, column=1, padx=5, pady=5)
    applicant_id_entry.insert(0, application[1])
    applicant_id_entry.config(state='readonly')

    ttk.Label(review_window, text="申请人ID:").grid(row=2, column=0, padx=5, pady=5)
    room_id_entry = ttk.Entry(review_window)
    room_id_entry.grid(row=2, column=1, padx=5, pady=5)
    room_id_entry.insert(0, application[2])
    room_id_entry.config(state='readonly')

    ttk.Label(review_window, text="申请时间:").grid(row=3, column=0, padx=5, pady=5)
    application_time_entry = ttk.Entry(review_window)
    application_time_entry.grid(row=3, column=1, padx=5, pady=5)
    application_time_entry.insert(0, application[3])
    application_time_entry.config(state='readonly')

    status_var = tk.StringVar(value=application[4])
    ttk.Label(review_window, text="状态:").grid(row=4, column=0, padx=5, pady=5)
    status_combobox = ttk.Combobox(review_window, textvariable=status_var,
                                   values=["待审核", "已批准", "已拒绝"])
    status_combobox.grid(row=4, column=1, padx=5, pady=5)

    def save_review():
        status = status_var.get()
        if status == "已批准":
            teacher_info = query_teacher_info(application[1])
            if teacher_info:
                update_classroom(application[2], None, None, teacher_info[3])
        if review_application(application[0], status):
            messagebox.showinfo("成功", "申请状态已更新")
            review_window.destroy()
        else:
            messagebox.showerror("错误", "无法更新申请状态")

    ttk.Button(review_window, text="保存", command=save_review).grid(row=5, columnspan=2, padx=5, pady=5)


# 查询管理员信息
def query_admin(user_id):
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM Admin WHERE UserID = %s"
            cursor.execute(query, (user_id,))
            return cursor.fetchone()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询管理员信息时出错: {e}")
        return None
    finally:
        connection.close()

# 查询所有教室信息
def query_all_classrooms():
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM Classroom"
            cursor.execute(query)
            return cursor.fetchall()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询教室信息时出错: {e}")
        return None
    finally:
        connection.close()

# 查询所有课程信息
def query_all_courses():
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM Course"
            cursor.execute(query)
            return cursor.fetchall()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询课程信息时出错: {e}")
        return None
    finally:
        connection.close()

# 查询所有学生信息
def query_all_students():
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM Student"
            cursor.execute(query)
            return cursor.fetchall()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询学生信息时出错: {e}")
        return None
    finally:
        connection.close()

# 查询所有教师信息
def query_all_teachers():
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM Teacher"
            cursor.execute(query)
            return cursor.fetchall()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询教师信息时出错: {e}")
        return None
    finally:
        connection.close()

# 查询所有教室申请信息
def query_all_applications():
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM ClassroomApplication"
            cursor.execute(query)
            return cursor.fetchall()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询教室申请信息时出错: {e}")
        return None
    finally:
        connection.close()

# 更新教室信息
def update_classroom(room_id, capacity, is_occupied, course_major):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "UPDATE Classroom SET Capacity = %s, IsOccupied = %s, CourseMajor = %s WHERE RoomID = %s"
            cursor.execute(query, (capacity, is_occupied, course_major, room_id))
            connection.commit()
            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"更新教室信息时出错: {e}")
        return False
    finally:
        connection.close()


# 更新课程信息
def update_course(course_id, course_name, teacher_id, class_time, enrollment):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "UPDATE Course SET CourseName = %s, TeacherID = %s, ClassTime = %s, Enrollment = %s WHERE CourseID = %s"
            cursor.execute(query, (course_name, teacher_id, class_time, enrollment, course_id))
            connection.commit()
            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"更新课程信息时出错: {e}")
        return False
    finally:
        connection.close()

# 更新学生信息
def update_student(student_id, name, major, class_, gender):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "UPDATE Student SET Name = %s, Major = %s, Class = %s, Gender = %s WHERE StudentID = %s"
            cursor.execute(query, (name, major, class_, gender, student_id))
            connection.commit()
            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"更新学生信息时出错: {e}")
        return False
    finally:
        connection.close()

# 更新教师信息
def update_teacher(teacher_id, name, title, college):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "UPDATE Teacher SET Name = %s, Title = %s, College = %s WHERE TeacherID = %s"
            cursor.execute(query, (name, title, college, teacher_id))
            connection.commit()
            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"更新教师信息时出错: {e}")
        return False
    finally:
        connection.close()

# 审核教室申请
def review_application_detail(self, application):
    review_window = tk.Toplevel(self)
    review_window.title("审核教室申请")

    ttk.Label(review_window, text="教室编号:").grid(row=0, column=0, padx=5, pady=5)
    application_id_entry = ttk.Entry(review_window)
    application_id_entry.grid(row=0, column=1, padx=5, pady=5)
    application_id_entry.insert(0, application[0])
    application_id_entry.config(state='readonly')

    ttk.Label(review_window, text="申请编号:").grid(row=1, column=0, padx=5, pady=5)
    applicant_id_entry = ttk.Entry(review_window)
    applicant_id_entry.grid(row=1, column=1, padx=5, pady=5)
    applicant_id_entry.insert(0, application[1])
    applicant_id_entry.config(state='readonly')

    ttk.Label(review_window, text="申请人ID:").grid(row=2, column=0, padx=5, pady=5)
    room_id_entry = ttk.Entry(review_window)
    room_id_entry.grid(row=2, column=1, padx=5, pady=5)
    room_id_entry.insert(0, application[2])
    room_id_entry.config(state='readonly')

    ttk.Label(review_window, text="申请时间:").grid(row=3, column=0, padx=5, pady=5)
    application_time_entry = ttk.Entry(review_window)
    application_time_entry.grid(row=3, column=1, padx=5, pady=5)
    application_time_entry.insert(0, application[3])
    application_time_entry.config(state='readonly')

    status_var = tk.StringVar(value=application[4])
    ttk.Label(review_window, text="状态:").grid(row=4, column=0, padx=5, pady=5)
    status_combobox = ttk.Combobox(review_window, textvariable=status_var,
                                   values=["待审核", "已批准", "已拒绝"])
    status_combobox.grid(row=4, column=1, padx=5, pady=5)

    def save_review():
        status = status_var.get()
        if status == "已批准":
            teacher_info = query_teacher_info(application[1])
            if teacher_info:
                update_classroom(application[2], None, None, teacher_info[3])
        if review_application(application[0], status):
            messagebox.showinfo("成功", "申请状态已更新")
            review_window.destroy()
        else:
            messagebox.showerror("错误", "无法更新申请状态")

    ttk.Button(review_window, text="保存", command=save_review).grid(row=5, columnspan=2, padx=5, pady=5)


# 查询学生个人信息
def query_student_info(user_id):
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM Student WHERE UserID = %s"
            cursor.execute(query, (user_id,))
            return cursor.fetchone()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询学生信息时出错: {e}")
        return None
    finally:
        connection.close()

def query_teacher_info(user_id):
    connection = connect_db()
    if connection is None:
        return None

    try:
        with connection.cursor() as cursor:
            query = "SELECT * FROM Teacher WHERE UserID = %s"
            cursor.execute(query, (user_id,))
            return cursor.fetchone()
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"查询教师信息时出错: {e}")
        return None
    finally:
        connection.close()

# 学生选课
def enroll_course(student_id, course_id):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "INSERT INTO Enrollment (StudentID, CourseID) VALUES (%s, %s)"
            cursor.execute(query, (student_id, course_id))
            connection.commit()
            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"选课时出错: {e}")
        return False
    finally:
        connection.close()

# 教师申请教室
# 教师申请教室
def apply_for_classroom(teacher_id, room_id, application_time):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "INSERT INTO ClassroomApplication (TeacherID, RoomID, ApplicationTime, Status) VALUES (%s, %s, %s, '待审核')"
            cursor.execute(query, (teacher_id, room_id, application_time))
            connection.commit()

            # 获取自动生成的ApplicationID
            application_id = cursor.lastrowid

            # 更新申请表中的ApplicantID和TeacherID
            update_query = "UPDATE ClassroomApplication SET ApplicantID = %s WHERE ApplicationID = %s"
            cursor.execute(update_query, (teacher_id, application_id))
            connection.commit()

            teacher_info = query_teacher_info(teacher_id)
            if teacher_info:
                update_query = "UPDATE ClassroomApplication SET TeacherID = %s WHERE ApplicationID = %s"
                cursor.execute(update_query, (teacher_info[0], application_id))
                connection.commit()

            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"申请教室时出错: {e}")
        return False
    finally:
        connection.close()

# 删除学生信息
def delete_student(student_id):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "DELETE FROM Student WHERE StudentID = %s"
            cursor.execute(query, (student_id,))
            connection.commit()
            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"删除学生信息时出错: {e}")
        return False
    finally:
        connection.close()

# 删除教师信息
def delete_teacher(teacher_id):
    connection = connect_db()
    if connection is None:
        return False

    try:
        with connection.cursor() as cursor:
            query = "DELETE FROM Teacher WHERE TeacherID = %s"
            cursor.execute(query, (teacher_id,))
            connection.commit()
            return True
    except pymysql.MySQLError as e:
        messagebox.showerror("数据库错误", f"删除教师信息时出错: {e}")
        return False
    finally:
        connection.close()



# 学生界面功能实现
class StudentApp:
    def __init__(self, master, user_id):
        self.master = master
        self.user_id = user_id
        self.current_frame = None
        self.create_student_frame()

    def destroy_current_frame(self):
        if self.current_frame:
            self.current_frame.destroy()

    def create_student_frame(self):
        self.destroy_current_frame()
        student_frame = ttk.Frame(self.master)
        student_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = student_frame

        # 显示个人信息
        student_info = query_student_info(self.user_id)
        if student_info:
            info_label = ttk.Label(student_frame,
                                   text=f"学生编号: {student_info[0]}, 姓名: {student_info[1]}, 专业: {student_info[2]}, 班级: {student_info[3]}, 性别: {student_info[4]}")
            info_label.pack(pady=10)
        else:
            info_label = ttk.Label(student_frame, text="无法获取学生信息")
            info_label.pack(pady=10)

        ttk.Button(student_frame, text="查看课程", command=self.view_courses).pack(pady=5)
        ttk.Button(student_frame, text="查看教室信息", command=self.view_classrooms).pack(pady=5)

    def view_courses(self):
        self.destroy_current_frame()
        view_courses_frame = ttk.Frame(self.master)
        view_courses_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = view_courses_frame

        # 从数据库中查询课程信息并显示
        courses = query_all_courses()
        for course in courses:
            ttk.Label(view_courses_frame, text=f"课程编号: {course[0]}, 课程名称: {course[1]}, 教师编号: {course[2]}, 上课时间: {course[3]}, 选课人数: {course[4]}").pack(pady=5)

        ttk.Button(view_courses_frame, text="返回", command=self.create_student_frame).pack(pady=5)

    def view_classrooms(self):
        self.destroy_current_frame()
        view_classrooms_frame = ttk.Frame(self.master)
        view_classrooms_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = view_classrooms_frame

        # 从数据库中查询教室信息并显示
        classrooms = query_all_classrooms()
        for classroom in classrooms:
            ttk.Label(view_classrooms_frame, text=f"教室编号: {classroom[0]}, 容量: {classroom[1]}, 是否被占用: {classroom[2]}, 课程专业: {classroom[3]}").pack(pady=5)

        ttk.Button(view_classrooms_frame, text="返回", command=self.create_student_frame).pack(pady=5)

class TeacherApp:
    def __init__(self, master, user_id):
        self.master = master
        self.user_id = user_id
        self.current_frame = None
        self.create_teacher_frame()

    def destroy_current_frame(self):
        if self.current_frame:
            self.current_frame.destroy()

    def create_teacher_frame(self):
        self.destroy_current_frame()
        teacher_frame = ttk.Frame(self.master)
        teacher_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = teacher_frame

        # 显示个人信息
        teacher_info = query_teacher_info(self.user_id)
        if teacher_info:
            info_label = ttk.Label(teacher_frame,
                                   text=f"教师编号: {teacher_info[0]}, 姓名: {teacher_info[1]}, 职称: {teacher_info[2]}, 学院: {teacher_info[3]}")
            info_label.pack(pady=10)
        else:
            info_label = ttk.Label(teacher_frame, text="无法获取教师信息")
            info_label.pack(pady=10)

        ttk.Button(teacher_frame, text="查看课程", command=self.view_courses).pack(pady=5)
        ttk.Button(teacher_frame, text="申请教室", command=self.apply_for_classroom).pack(pady=5)
        ttk.Button(teacher_frame, text="查看教室信息", command=self.view_classrooms).pack(pady=5)

    def view_courses(self):
        self.destroy_current_frame()
        view_courses_frame = ttk.Frame(self.master)
        view_courses_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = view_courses_frame

        # 从数据库中查询课程信息并显示
        courses = query_all_courses()
        for course in courses:
            ttk.Label(view_courses_frame, text=f"课程编号: {course[0]}, 课程名称: {course[1]}, 教师编号: {course[2]}, 上课时间: {course[3]}, 选课人数: {course[4]}").pack(pady=5)

        ttk.Button(view_courses_frame, text="返回", command=self.create_teacher_frame).pack(pady=5)

    def apply_for_classroom(self):
        self.destroy_current_frame()
        apply_classroom_frame = ttk.Frame(self.master)
        apply_classroom_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = apply_classroom_frame

        ttk.Label(apply_classroom_frame, text="教室编号:").grid(row=0, column=0, padx=5, pady=5)
        room_id_entry = ttk.Entry(apply_classroom_frame)
        room_id_entry.grid(row=0, column=1, padx=5, pady=5)

        ttk.Label(apply_classroom_frame, text="申请时间:").grid(row=1, column=0, padx=5, pady=5)
        application_time_entry = ttk.Entry(apply_classroom_frame)
        application_time_entry.grid(row=1, column=1, padx=5, pady=5)

        def submit_application():
            room_id = room_id_entry.get()
            application_time = application_time_entry.get()
            if apply_for_classroom(self.user_id, room_id, application_time):
                messagebox.showinfo("成功", "教室申请已提交")
                self.create_teacher_frame()
            else:
                messagebox.showerror("错误", "无法提交教室申请")

        ttk.Button(apply_classroom_frame, text="提交申请", command=submit_application).grid(row=2, columnspan=2, padx=5, pady=5)
        ttk.Button(apply_classroom_frame, text="返回", command=self.create_teacher_frame).grid(row=3, columnspan=2, padx=5, pady=5)

    def view_classrooms(self):
        self.destroy_current_frame()
        view_classrooms_frame = ttk.Frame(self.master)
        view_classrooms_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = view_classrooms_frame

        # 从数据库中查询教室信息并显示
        classrooms = query_all_classrooms()
        for classroom in classrooms:
            ttk.Label(view_classrooms_frame, text=f"教室编号: {classroom[0]}, 容量: {classroom[1]}, 是否被占用: {classroom[2]}, 课程专业: {classroom[3]}").pack(pady=5)

        ttk.Button(view_classrooms_frame, text="返回", command=self.create_teacher_frame).pack(pady=5)




# 主应用程序类
class ClassroomManagementApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("教室管理系统")
        self.geometry("800x600")
        self.user_type = None
        self.user_id = None
        self.current_frame = None  # 初始化为None
        # 登录界面
        self.create_login_frame()

    def destroy_current_frame(self):
        if self.current_frame:
            self.current_frame.destroy()

    def create_login_frame(self):
        self.login_frame = ttk.Frame(self)
        self.login_frame.pack(fill=tk.BOTH, expand=True)

        ttk.Label(self.login_frame, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
        self.username_entry = ttk.Entry(self.login_frame)
        self.username_entry.grid(row=0, column=1, padx=5, pady=5)

        ttk.Label(self.login_frame, text="密码:").grid(row=1, column=0, padx=5, pady=5)
        self.password_entry = ttk.Entry(self.login_frame, show="*")
        self.password_entry.grid(row=1, column=1, padx=5, pady=5)

        login_button = ttk.Button(self.login_frame, text="登录", command=self.login)
        login_button.grid(row=2, columnspan=2, padx=5, pady=5)

    def login(self):
        username = self.username_entry.get()
        password = self.password_entry.get()
        user = query_user(username, password)
        if user:
            self.user_type = user[3]  # 假设 UserType 在第 4 列
            self.user_id = user[0]  # 假设 UserID 在第 1 列
            self.login_frame.destroy()
            self.create_main_frame()
        else:
            messagebox.showerror("错误", "用户名或密码错误")

    def create_main_frame(self):
        # 根据用户类型创建不同的主界面
        if self.user_type == '管理员':
            self.create_admin_frame()
        elif self.user_type == '教师':
            self.teacher_app = TeacherApp(self, self.user_id)
        elif self.user_type == '学生':
            self.student_app = StudentApp(self, self.user_id)

    def create_admin_frame(self):
        self.destroy_current_frame()  # 销毁当前的管理界面
        admin_frame = ttk.Frame(self)
        admin_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = admin_frame  # 更新当前界面

        admin_info = query_admin(self.user_id)
        if admin_info:
            ttk.Label(admin_frame, text=f"管理员: {admin_info[1]}").pack(pady=10)
            ttk.Label(admin_frame, text=f"部门: {admin_info[2]}").pack(pady=10)
        else:
            ttk.Label(admin_frame, text="无法获取管理员信息").pack(pady=10)

        # 管理教室信息
        ttk.Button(admin_frame, text="管理教室信息", command=self.manage_classrooms).pack(pady=5)
        # 管理课程信息
        ttk.Button(admin_frame, text="管理课程信息", command=self.manage_courses).pack(pady=5)
        # 管理学生信息
        ttk.Button(admin_frame, text="管理学生信息", command=self.manage_students).pack(pady=5)
        # 管理教师信息
        ttk.Button(admin_frame, text="管理教师信息", command=self.manage_teachers).pack(pady=5)
        # 审核教室申请
        ttk.Button(admin_frame, text="审核教室申请", command=self.review_applications).pack(pady=5)

    def manage_classrooms(self):
        self.destroy_current_frame()  # 销毁当前界面
        classrooms = query_all_classrooms()
        if not classrooms:
            messagebox.showerror("错误", "无法获取教室信息")
            return

        manage_frame = ttk.Frame(self)
        manage_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = manage_frame  # 更新当前界面

        # 添加返回按钮
        ttk.Button(manage_frame, text="返回", command=self.create_admin_frame).pack(pady=5)

        for classroom in classrooms:
            frame = ttk.Frame(manage_frame)
            frame.pack(fill=tk.X, padx=5, pady=5)

            ttk.Label(frame,
                      text=f"教室编号: {classroom[0]}, 容量: {classroom[1]}, 是否被占用: {classroom[2]}").pack(
                side=tk.LEFT)
            ttk.Button(frame, text="编辑", command=lambda c=classroom: self.edit_classroom(c)).pack(side=tk.RIGHT)

    def edit_classroom(self, classroom):
        edit_window = tk.Toplevel(self)
        edit_window.title("编辑教室信息")

        ttk.Label(edit_window, text="教室编号:").grid(row=0, column=0, padx=5, pady=5)
        room_id_entry = ttk.Entry(edit_window)
        room_id_entry.grid(row=0, column=1, padx=5, pady=5)
        room_id_entry.insert(0, classroom[0])
        room_id_entry.config(state='readonly')

        ttk.Label(edit_window, text="容量:").grid(row=1, column=0, padx=5, pady=5)
        capacity_entry = ttk.Entry(edit_window)
        capacity_entry.grid(row=1, column=1, padx=5, pady=5)
        capacity_entry.insert(0, classroom[1])

        ttk.Label(edit_window, text="是否被占用:").grid(row=2, column=0, padx=5, pady=5)
        is_occupied_var = tk.BooleanVar(value=classroom[2])
        is_occupied_check = ttk.Checkbutton(edit_window, variable=is_occupied_var)
        is_occupied_check.grid(row=2, column=1, padx=5, pady=5)

        def save_classroom():
            capacity = capacity_entry.get()
            is_occupied = is_occupied_var.get()
            if update_classroom(classroom[0], capacity, is_occupied):
                messagebox.showinfo("成功", "教室信息已更新")
                edit_window.destroy()
            else:
                messagebox.showerror("错误", "无法更新教室信息")

        ttk.Button(edit_window, text="保存", command=save_classroom).grid(row=3, columnspan=2, padx=5, pady=5)

    def manage_courses(self):
        self.destroy_current_frame()  # 销毁当前界面
        courses = query_all_courses()
        if not courses:
            messagebox.showerror("错误", "无法获取课程信息")
            return

        manage_frame = ttk.Frame(self)
        manage_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = manage_frame  # 更新当前界面

        # 添加返回按钮
        ttk.Button(manage_frame, text="返回", command=self.create_admin_frame).pack(pady=5)

        for course in courses:
            frame = ttk.Frame(manage_frame)
            frame.pack(fill=tk.X, padx=5, pady=5)

            ttk.Label(frame,
                      text=f"课程编号: {course[0]}, 课程名称: {course[1]}, 授课教师ID: {course[2]}, 上课时间: {course[3]}, 选课学生数量: {course[4]}").pack(
                side=tk.LEFT)
            ttk.Button(frame, text="编辑", command=lambda c=course: self.edit_course(c)).pack(side=tk.RIGHT)

    def edit_course(self, course):
        edit_window = tk.Toplevel(self)
        edit_window.title("编辑课程信息")

        ttk.Label(edit_window, text="课程编号:").grid(row=0, column=0, padx=5, pady=5)
        course_id_entry = ttk.Entry(edit_window)
        course_id_entry.grid(row=0, column=1, padx=5, pady=5)
        course_id_entry.insert(0, course[0])
        course_id_entry.config(state='readonly')

        ttk.Label(edit_window, text="课程名称:").grid(row=1, column=0, padx=5, pady=5)
        course_name_entry = ttk.Entry(edit_window)
        course_name_entry.grid(row=1, column=1, padx=5, pady=5)
        course_name_entry.insert(0, course[1])

        ttk.Label(edit_window, text="授课教师ID:").grid(row=2, column=0, padx=5, pady=5)
        teacher_id_entry = ttk.Entry(edit_window)
        teacher_id_entry.grid(row=2, column=1, padx=5, pady=5)
        teacher_id_entry.insert(0, course[2])

        ttk.Label(edit_window, text="上课时间:").grid(row=3, column=0, padx=5, pady=5)
        class_time_entry = ttk.Entry(edit_window)
        class_time_entry.grid(row=3, column=1, padx=5, pady=5)
        class_time_entry.insert(0, course[3])

        ttk.Label(edit_window, text="选课学生数量:").grid(row=4, column=0, padx=5, pady=5)
        enrollment_entry = ttk.Entry(edit_window)
        enrollment_entry.grid(row=4, column=1, padx=5, pady=5)
        enrollment_entry.insert(0, course[4])

        def save_course():
            course_name = course_name_entry.get()
            teacher_id = teacher_id_entry.get()
            class_time = class_time_entry.get()
            enrollment = enrollment_entry.get()
            if update_course(course[0], course_name, teacher_id, class_time, enrollment):
                messagebox.showinfo("成功", "课程信息已更新")
                edit_window.destroy()
            else:
                messagebox.showerror("错误", "无法更新课程信息")

        ttk.Button(edit_window, text="保存", command=save_course).grid(row=5, columnspan=2, padx=5, pady=5)

    def manage_students(self):
        self.destroy_current_frame()  # 销毁当前界面
        students = query_all_students()
        if not students:
            messagebox.showerror("错误", "无法获取学生信息")
            return

        manage_frame = ttk.Frame(self)
        manage_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = manage_frame  # 更新当前界面

        # 添加返回按钮
        ttk.Button(manage_frame, text="返回", command=self.create_admin_frame).pack(pady=5)

        for student in students:
            frame = ttk.Frame(manage_frame)
            frame.pack(fill=tk.X, padx=5, pady=5)

            ttk.Label(frame,
                      text=f"学生编号: {student[0]}, 姓名: {student[1]}, 专业: {student[2]}, 班级: {student[3]}, 性别: {student[4]}").pack(
                side=tk.LEFT)
            ttk.Button(frame, text="编辑", command=lambda s=student: self.edit_student(s)).pack(side=tk.RIGHT)
            ttk.Button(frame, text="删除", command=lambda s=student: self.confirm_delete_student(s)).pack(side=tk.RIGHT)

    def confirm_delete_student(self, student):
        confirm = messagebox.askyesno("确认删除", f"确定要删除学生 {student[1]} 的信息吗？")
        if confirm:
            if delete_student(student[0]):
                messagebox.showinfo("成功", "学生信息已删除")
                self.manage_students()  # 刷新学生信息列表
            else:
                messagebox.showerror("错误", "无法删除学生信息")

    def edit_student(self, student):
        edit_window = tk.Toplevel(self)
        edit_window.title("编辑学生信息")

        ttk.Label(edit_window, text="学生编号:").grid(row=0, column=0, padx=5, pady=5)
        student_id_entry = ttk.Entry(edit_window)
        student_id_entry.grid(row=0, column=1, padx=5, pady=5)
        student_id_entry.insert(0, student[0])
        student_id_entry.config(state='readonly')

        ttk.Label(edit_window, text="姓名:").grid(row=1, column=0, padx=5, pady=5)
        name_entry = ttk.Entry(edit_window)
        name_entry.grid(row=1, column=1, padx=5, pady=5)
        name_entry.insert(0, student[1])

        ttk.Label(edit_window, text="专业:").grid(row=2, column=0, padx=5, pady=5)
        major_entry = ttk.Entry(edit_window)
        major_entry.grid(row=2, column=1, padx=5, pady=5)
        major_entry.insert(0, student[2])

        ttk.Label(edit_window, text="班级:").grid(row=3, column=0, padx=5, pady=5)
        class_entry = ttk.Entry(edit_window)
        class_entry.grid(row=3, column=1, padx=5, pady=5)
        class_entry.insert(0, student[3])

        ttk.Label(edit_window, text="性别:").grid(row=4, column=0, padx=5, pady=5)
        gender_entry = ttk.Entry(edit_window)
        gender_entry.grid(row=4, column=1, padx=5, pady=5)
        gender_entry.insert(0, student[4])

        def save_student():
            name = name_entry.get()
            major = major_entry.get()
            class_ = class_entry.get()
            gender = gender_entry.get()
            if update_student(student[0], name, major, class_, gender):
                messagebox.showinfo("成功", "学生信息已更新")
                edit_window.destroy()
            else:
                messagebox.showerror("错误", "无法更新学生信息")

        ttk.Button(edit_window, text="保存", command=save_student).grid(row=5, columnspan=2, padx=5, pady=5)

    def manage_teachers(self):
        self.destroy_current_frame()  # 销毁当前界面
        teachers = query_all_teachers()
        if not teachers:
            messagebox.showerror("错误", "无法获取教师信息")
            return

        manage_frame = ttk.Frame(self)
        manage_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = manage_frame  # 更新当前界面

        # 添加返回按钮
        ttk.Button(manage_frame, text="返回", command=self.create_admin_frame).pack(pady=5)

        for teacher in teachers:
            frame = ttk.Frame(manage_frame)
            frame.pack(fill=tk.X, padx=5, pady=5)

            ttk.Label(frame,
                      text=f"教师编号: {teacher[0]}, 姓名: {teacher[1]}, 职称: {teacher[2]}, 学院: {teacher[3]}").pack(
                side=tk.LEFT)
            ttk.Button(frame, text="编辑", command=lambda t=teacher: self.edit_teacher(t)).pack(side=tk.RIGHT)
            ttk.Button(frame, text="删除", command=lambda t=teacher: self.confirm_delete_teacher(t)).pack(side=tk.RIGHT)

    def confirm_delete_teacher(self, teacher):
        confirm = messagebox.askyesno("确认删除", f"确定要删除教师 {teacher[1]} 的信息吗？")
        if confirm:
            if delete_teacher(teacher[0]):
                messagebox.showinfo("成功", "教师信息已删除")
                self.manage_teachers()  # 刷新教师信息列表
            else:
                messagebox.showerror("错误", "无法删除教师信息")

    def edit_teacher(self, teacher):
        edit_window = tk.Toplevel(self)
        edit_window.title("编辑教师信息")

        ttk.Label(edit_window, text="教师编号:").grid(row=0, column=0, padx=5, pady=5)
        teacher_id_entry = ttk.Entry(edit_window)
        teacher_id_entry.grid(row=0, column=1, padx=5, pady=5)
        teacher_id_entry.insert(0, teacher[0])
        teacher_id_entry.config(state='readonly')

        ttk.Label(edit_window, text="姓名:").grid(row=1, column=0, padx=5, pady=5)
        name_entry = ttk.Entry(edit_window)
        name_entry.grid(row=1, column=1, padx=5, pady=5)
        name_entry.insert(0, teacher[1])

        ttk.Label(edit_window, text="职称:").grid(row=2, column=0, padx=5, pady=5)
        title_entry = ttk.Entry(edit_window)
        title_entry.grid(row=2, column=1, padx=5, pady=5)
        title_entry.insert(0, teacher[2])

        ttk.Label(edit_window, text="学院:").grid(row=3, column=0, padx=5, pady=5)
        college_entry = ttk.Entry(edit_window)
        college_entry.grid(row=3, column=1, padx=5, pady=5)
        college_entry.insert(0, teacher[3])

        def save_teacher():
            name = name_entry.get()
            title = title_entry.get()
            college = college_entry.get()
            if update_teacher(teacher[0], name, title, college):
                messagebox.showinfo("成功", "教师信息已更新")
                edit_window.destroy()
            else:
                messagebox.showerror("错误", "无法更新教师信息")

        ttk.Button(edit_window, text="保存", command=save_teacher).grid(row=4, columnspan=2, padx=5, pady=5)

    def review_applications(self):
        self.destroy_current_frame()  # 销毁当前界面
        applications = query_all_applications()
        if not applications:
            messagebox.showerror("错误", "无法获取教室申请信息")
            return

        review_frame = ttk.Frame(self)
        review_frame.pack(fill=tk.BOTH, expand=True)
        self.current_frame = review_frame  # 更新当前界面

        # 添加返回按钮
        ttk.Button(review_frame, text="返回", command=self.create_admin_frame).pack(pady=5)

        for application in applications:
            frame = ttk.Frame(review_frame)
            frame.pack(fill=tk.X, padx=5, pady=5)

            ttk.Label(frame,
                      text=f"申请编号: {application[0]}, 教室编号: {application[1]}, 申请人ID: {application[2]}, 申请时间: {application[3]}, 状态: {application[4]}").pack(
                side=tk.LEFT)
            ttk.Button(frame, text="审核", command=lambda a=application: self.review_application_detail(a)).pack(
                side=tk.RIGHT)

    def review_application_detail(self, application):
        review_window = tk.Toplevel(self)
        review_window.title("审核教室申请")

        ttk.Label(review_window, text="申请编号:").grid(row=0, column=0, padx=5, pady=5)
        application_id_entry = ttk.Entry(review_window)
        application_id_entry.grid(row=0, column=1, padx=5, pady=5)
        application_id_entry.insert(0, application[0])
        application_id_entry.config(state='readonly')

        ttk.Label(review_window, text="教室编号:").grid(row=1, column=0, padx=5, pady=5)
        applicant_id_entry = ttk.Entry(review_window)
        applicant_id_entry.grid(row=1, column=1, padx=5, pady=5)
        applicant_id_entry.insert(0, application[1])
        applicant_id_entry.config(state='readonly')

        ttk.Label(review_window, text="申请人ID:").grid(row=2, column=0, padx=5, pady=5)
        room_id_entry = ttk.Entry(review_window)
        room_id_entry.grid(row=2, column=1, padx=5, pady=5)
        room_id_entry.insert(0, application[2])
        room_id_entry.config(state='readonly')

        ttk.Label(review_window, text="申请时间:").grid(row=3, column=0, padx=5, pady=5)
        application_time_entry = ttk.Entry(review_window)
        application_time_entry.grid(row=3, column=1, padx=5, pady=5)
        application_time_entry.insert(0, application[3])
        application_time_entry.config(state='readonly')

        status_var = tk.StringVar(value=application[4])
        ttk.Label(review_window, text="状态:").grid(row=4, column=0, padx=5, pady=5)
        status_combobox = ttk.Combobox(review_window, textvariable=status_var,
                                       values=["待审核", "已批准", "已拒绝"])
        status_combobox.grid(row=4, column=1, padx=5, pady=5)

        def save_review():
            status = status_var.get()
            if review_application(application[0], status):
                messagebox.showinfo("成功", "申请状态已更新")
                review_window.destroy()
            else:
                messagebox.showerror("错误", "无法更新申请状态")

        ttk.Button(review_window, text="保存", command=save_review).grid(row=5, columnspan=2, padx=5, pady=5)

if __name__ == "__main__":
    app = ClassroomManagementApp()
    app.mainloop()
